#!/bin/bash

# 工程实践平台重启脚本
# 使用方法: ./scripts/restart.sh

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查脚本是否在项目根目录运行
check_project_root() {
    if [[ ! -f "pom.xml" ]] && [[ ! -f "app.jar" ]]; then
        log_error "请在项目根目录运行此脚本"
        exit 1
    fi
}

# 重启主应用
restart_main_app() {
    log_info "重启主应用..."
    
    # 停止应用
    if [[ -f "app.pid" ]]; then
        local PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            log_info "停止应用进程 (PID: $PID)..."
            kill $PID
            
            # 等待进程结束
            local wait_time=0
            local max_wait=30
            while kill -0 $PID 2>/dev/null && [[ $wait_time -lt $max_wait ]]; do
                sleep 1
                ((wait_time++))
                echo -n "."
            done
            
            if kill -0 $PID 2>/dev/null; then
                log_warning "应用未响应，强制停止..."
                kill -9 $PID
            fi
            
            rm -f app.pid
            log_success "应用已停止"
        else
            log_warning "应用进程不存在，清理PID文件"
            rm -f app.pid
        fi
    fi
    
    # 等待端口释放
    log_info "等待端口释放..."
    local wait_time=0
    local max_wait=30
    while netstat -tlnp 2>/dev/null | grep -q ":8080" && [[ $wait_time -lt $max_wait ]]; do
        sleep 1
        ((wait_time++))
        echo -n "."
    done
    
    if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
        log_warning "端口8080仍在占用，等待更长时间..."
        sleep 10
    fi
    
    # 启动应用
    log_info "启动应用..."
    if [[ -f "app.jar" ]]; then
        mkdir -p logs
        nohup java -jar app.jar --spring.profiles.active=prod > logs/app.log 2>&1 &
        echo $! > app.pid
        log_success "应用启动完成，PID: $(cat app.pid)"
    else
        log_error "app.jar文件不存在，请先构建项目"
        exit 1
    fi
}

# 重启用户环境
restart_user_environments() {
    log_info "重启用户环境..."
    
    if [[ -d "users" ]]; then
        local user_dirs=($(find users -maxdepth 1 -type d -name "user*" 2>/dev/null))
        local total_users=${#user_dirs[@]}
        
        if [[ $total_users -gt 0 ]]; then
            echo "发现 $total_users 个用户环境，正在重启..."
            
            for user_dir in "${user_dirs[@]}"; do
                local user_id=$(basename "$user_dir")
                local compose_file="$user_dir/docker-compose.yml"
                
                if [[ -f "$compose_file" ]]; then
                    log_info "重启用户环境: $user_id"
                    cd "$user_dir"
                    
                    # 停止环境
                    if docker-compose down 2>/dev/null; then
                        echo "  ✅ $user_id: 已停止"
                    fi
                    
                    # 启动环境
                    if docker-compose up -d 2>/dev/null; then
                        echo "  ✅ $user_id: 已启动"
                    else
                        echo "  ❌ $user_id: 启动失败"
                    fi
                    
                    cd - > /dev/null
                fi
            done
        else
            log_info "无用户环境需要重启"
        fi
    else
        log_info "用户目录不存在"
    fi
}

# 重启核心服务
restart_core_services() {
    log_info "重启核心服务..."
    
    # 重启MySQL
    if docker ps | grep -q practice-platform-mysql; then
        log_info "重启MySQL服务..."
        docker restart practice-platform-mysql
        log_success "MySQL服务已重启"
    else
        log_info "MySQL服务未运行，跳过重启"
    fi
    
    # 重启Redis
    if docker ps | grep -q practice-platform-redis; then
        log_info "重启Redis服务..."
        docker restart practice-platform-redis
        log_success "Redis服务已重启"
    else
        log_info "Redis服务未运行，跳过重启"
    fi
    
    # 重启RabbitMQ
    if docker ps | grep -q practice-platform-rabbitmq; then
        log_info "重启RabbitMQ服务..."
        docker restart practice-platform-rabbitmq
        log_success "RabbitMQ服务已重启"
    else
        log_info "RabbitMQ服务未运行，跳过重启"
    fi
    
    # 重启Elasticsearch
    if docker ps | grep -q practice-platform-elasticsearch; then
        log_info "重启Elasticsearch服务..."
        docker restart practice-platform-elasticsearch
        log_success "Elasticsearch服务已重启"
    else
        log_info "Elasticsearch服务未运行，跳过重启"
    fi
}

# 等待服务启动
wait_for_services() {
    log_info "等待服务启动..."
    
    # 等待主应用启动
    local max_attempts=30
    local attempt=1
    
    while [[ $attempt -le $max_attempts ]]; do
        if curl -s http://localhost:8080/actuator/health &> /dev/null; then
            log_success "主应用启动成功！"
            break
        fi
        
        echo -n "."
        sleep 2
        ((attempt++))
        
        if [[ $attempt -gt $max_attempts ]]; then
            log_warning "主应用启动超时，但继续检查其他服务"
            break
        fi
    done
    
    # 等待MySQL启动
    if docker ps | grep -q practice-platform-mysql; then
        log_info "等待MySQL启动..."
        local mysql_attempts=0
        while [[ $mysql_attempts -lt 30 ]]; do
            if docker exec practice-platform-mysql mysql -u root -proot -e "SELECT 1;" &> /dev/null; then
                log_success "MySQL启动成功！"
                break
            fi
            sleep 2
            ((mysql_attempts++))
        done
    fi
}

# 显示重启结果
show_restart_result() {
    echo
    echo "=========================================="
    echo "重启结果"
    echo "=========================================="
    
    # 检查主应用
    if [[ -f "app.pid" ]]; then
        local PID=$(cat app.pid)
        if kill -0 $PID 2>/dev/null; then
            echo "✅ 主应用: 运行中 (PID: $PID)"
        else
            echo "❌ 主应用: 未运行"
        fi
    else
        echo "❌ 主应用: 未运行"
    fi
    
    # 检查端口监听
    if netstat -tlnp 2>/dev/null | grep -q ":8080"; then
        echo "✅ 端口8080: 正在监听"
    else
        echo "❌ 端口8080: 未监听"
    fi
    
    # 检查Docker容器
    local running_containers=$(docker ps --format "{{.Names}}" | grep -E "(practice-platform|mysql|redis|rabbitmq|elasticsearch)" || true)
    if [[ -n "$running_containers" ]]; then
        echo "✅ 运行中的容器:"
        echo "$running_containers" | while read container; do
            echo "  - $container"
        done
    else
        echo "❌ 无容器运行"
    fi
    
    echo "=========================================="
}

# 显示管理命令
show_management_commands() {
    echo
    echo "=========================================="
    echo "管理命令"
    echo "=========================================="
    echo "查看状态:   ./scripts/status.sh"
    echo "停止平台:   ./scripts/stop.sh"
    echo "查看日志:   tail -f logs/app.log"
    echo "=========================================="
}

# 主函数
main() {
    echo "=========================================="
    echo "工程实践平台重启脚本"
    echo "=========================================="
    echo
    
    # 检查环境
    check_project_root
    
    # 重启服务
    restart_main_app
    restart_core_services
    restart_user_environments
    
    # 等待启动
    wait_for_services
    
    # 显示结果
    show_restart_result
    show_management_commands
    
    log_success "平台重启完成！"
}

# 执行主函数
main "$@" 